Ext.define('TD.controller.task.ListController', {
    extend: 'Ext.app.Controller',
    
    stores: [
        'TaskStore'
    ],
    
    models: [
        'Task'
    ],
    
    views: [
        'task.EditView',
        'task.ListView'
    ],
    
    init: function() {
        this.control({
            'tasklist': {
                itemdblclick: this.editTask,
                itemcontextmenu: this.contextMenuShow,
                containercontextmenu: this.addContextMenuShow
            }
        });
    },

    editTask: function(grid, record) {
    	// get a task editTask widget (EditView)
    	var view = Ext.widget('taskedit');
    	
    	// put there a current record
    	// data from it will be put in the fields
        view.down('form').loadRecord(record);
    },
    
    addContextMenuShow: function(grid, event) {
    	event.preventDefault();
    	
    	var menu = new Ext.menu.Menu({
            items: [{
                text: 'Add',
                iconCls: 'add',
                handler: this.contextMenuAddTask
            }]        
        });

        menu.showAt(event.xy);
    },
    
    // TODO task#2
    contextMenuShow: function(grid, record, item, index, event, options) {
    	// Stop native handlers
    	event.preventDefault();
        
        var menu = new Ext.menu.Menu({
            items: [{
                text: 'Add',
                iconCls: 'add',
                handler: this.contextMenuAddTask
            }, {
                text: 'Edit',
                iconCls: 'edit',
                handler: this.contextMenuEditTask,
                record : record
            }, {
                text: 'Remove',
                iconCls: 'remove',
                handler: this.contextMenuRemoveTask,
                record : record
            }]            
        });

        menu.showAt(event.xy);
    },
    
    contextMenuAddTask: function(menu) {
        Ext.widget('taskedit');
    },
    
    contextMenuEditTask: function(menuItem) {
        var view = Ext.widget('taskedit');
        view.down('form').loadRecord(menuItem.record);
    },
    
    contextMenuRemoveTask: function(menuItem) {
    	Ext.Msg.show({
            title:'Delete record?',
            msg: 'Would you like to delete this record?',
            buttons: Ext.Msg.YESNOCANCEL,
            animEl: 'elId',
            icon: Ext.MessageBox.QUESTION,
            fn: function(btn) {
               if (btn == 'yes') {
           	       // TODO task#7
                   Ext.Ajax.request({
                       url: 'task/remove.json',
                       params: {
                           recordId: menuItem.record.data.id
                       },
                       // Server remove success
                       success: function(response){
                           Ext.widget('tasklist').getStore().remove(menuItem.record);
                       }
                   });
           	   }
            }
        });
    }
    
});